import { ref, computed } from 'vue'

export interface AudioPlayerState {
  isPlaying: boolean
  isPaused: boolean
  duration: number
  currentTime: number
  volume: number
  isLoading: boolean
  error: string | null
}

export function useAudioPlayer() {
  const audio = ref<HTMLAudioElement | null>(null)
  
  // 检测浏览器支持
  const isSupported = !!(window.Audio && window.HTMLAudioElement)
  
  const state = ref<AudioPlayerState>({
    isPlaying: false,
    isPaused: false,
    duration: 0,
    currentTime: 0,
    volume: 1,
    isLoading: false,
    error: null
  })

  // 创建音频元素
  const createAudio = () => {
    if (audio.value) {
      cleanup()
    }

    audio.value = new Audio()
    
    // 监听事件
    audio.value.addEventListener('loadstart', () => {
      state.value.isLoading = true
      state.value.error = null
    })

    audio.value.addEventListener('loadedmetadata', () => {
      state.value.duration = audio.value?.duration || 0
      state.value.isLoading = false
    })

    audio.value.addEventListener('canplay', () => {
      state.value.isLoading = false
    })

    audio.value.addEventListener('play', () => {
      state.value.isPlaying = true
      state.value.isPaused = false
    })

    audio.value.addEventListener('pause', () => {
      state.value.isPlaying = false
      state.value.isPaused = true
    })

    audio.value.addEventListener('ended', () => {
      state.value.isPlaying = false
      state.value.isPaused = false
      state.value.currentTime = 0
    })

    audio.value.addEventListener('timeupdate', () => {
      state.value.currentTime = audio.value?.currentTime || 0
    })

    audio.value.addEventListener('volumechange', () => {
      state.value.volume = audio.value?.volume || 1
    })

    audio.value.addEventListener('error', (e) => {
      state.value.error = '音频播放失败'
      state.value.isLoading = false
      state.value.isPlaying = false
      console.error('音频播放错误:', e)
    })
  }

  // 将PCM数据转换为WAV格式
  const pcmToWav = (pcmData: Uint8Array, sampleRate: number = 24000, channels: number = 1, bitDepth: number = 16): ArrayBuffer => {
    const length = pcmData.length
    const buffer = new ArrayBuffer(44 + length)
    const view = new DataView(buffer)
    
    // WAV文件头
    const writeString = (offset: number, string: string) => {
      for (let i = 0; i < string.length; i++) {
        view.setUint8(offset + i, string.charCodeAt(i))
      }
    }
    
    // RIFF标识符
    writeString(0, 'RIFF')
    view.setUint32(4, 36 + length, true) // 文件长度
    writeString(8, 'WAVE')
    
    // fmt子块
    writeString(12, 'fmt ')
    view.setUint32(16, 16, true) // fmt子块长度
    view.setUint16(20, 1, true) // 音频格式 (PCM)
    view.setUint16(22, channels, true) // 声道数
    view.setUint32(24, sampleRate, true) // 采样率
    view.setUint32(28, sampleRate * channels * bitDepth / 8, true) // 字节率
    view.setUint16(32, channels * bitDepth / 8, true) // 块对齐
    view.setUint16(34, bitDepth, true) // 位深度
    
    // data子块
    writeString(36, 'data')
    view.setUint32(40, length, true) // 数据长度
    
    // 复制PCM数据
    const dataView = new Uint8Array(buffer, 44)
    dataView.set(pcmData)
    
    return buffer
  }

  // 从Base64播放音频
  const playBase64Audio = async (base64Data: string, mimeType: string = 'audio/wav') => {
    return new Promise<boolean>((resolve, reject) => {
      try {
        if (!isSupported) {
          reject(new Error('浏览器不支持音频播放'))
          return
        }

        if (!audio.value) {
          createAudio()
        }

        state.value.error = null
        
        // 将Base64转换为字节数组
        const binaryString = atob(base64Data)
        const bytes = new Uint8Array(binaryString.length)
        for (let i = 0; i < binaryString.length; i++) {
          bytes[i] = binaryString.charCodeAt(i)
        }
        
        let audioBuffer: ArrayBuffer
        let finalMimeType = mimeType
        
        // 检测是否为PCM数据（阿里云TTS返回的格式）
        // PCM数据没有文件头，尝试转换为WAV格式
        if (mimeType === 'audio/pcm' || !hasAudioHeader(bytes)) {
          console.log('检测到PCM音频数据，转换为WAV格式')
          audioBuffer = pcmToWav(bytes, 24000, 1, 16) // 阿里云TTS的参数
          finalMimeType = 'audio/wav'
        } else {
          audioBuffer = bytes.buffer
        }
        
        const blob = new Blob([audioBuffer], { type: finalMimeType })
        const audioUrl = URL.createObjectURL(blob)
        
        if (audio.value) {
          const playPromise = new Promise<void>((playResolve, playReject) => {
            const onCanPlay = () => {
              audio.value!.removeEventListener('canplay', onCanPlay)
              audio.value!.removeEventListener('error', onError)
              audio.value!.play()
                .then(() => playResolve())
                .catch((error) => playReject(error))
            }
            
            const onError = (error: any) => {
              audio.value!.removeEventListener('canplay', onCanPlay)
              audio.value!.removeEventListener('error', onError)
              playReject(error)
            }
            
            audio.value!.addEventListener('canplay', onCanPlay)
            audio.value!.addEventListener('error', onError)
            audio.value!.src = audioUrl
          })
          
          playPromise
            .then(() => {
              console.log(`音频播放成功，格式: ${finalMimeType}`)
              resolve(true)
            })
            .catch((error) => {
              console.warn(`音频播放失败，格式: ${finalMimeType}`, error)
              URL.revokeObjectURL(audioUrl)
              resolve(false)
            })
        } else {
          resolve(false)
        }
      } catch (error) {
        console.error('播放Base64音频失败:', error)
        state.value.error = '音频播放失败'
        resolve(false)
      }
    })
  }

  // 检测是否有音频文件头
  const hasAudioHeader = (bytes: Uint8Array): boolean => {
    if (bytes.length < 4) return false
    
    // 检查常见音频格式的文件头
    const header = Array.from(bytes.slice(0, 4)).map(b => String.fromCharCode(b)).join('')
    
    // WAV: RIFF
    if (header === 'RIFF') return true
    
    // MP3: ID3 或 0xFF 0xFB
    if (header.startsWith('ID3') || (bytes[0] === 0xFF && (bytes[1] & 0xE0) === 0xE0)) return true
    
    // OGG: OggS
    if (header === 'OggS') return true
    
    return false
  }

  // 从URL播放音频
  const playFromUrl = async (url: string) => {
    try {
      if (!isSupported) {
        throw new Error('浏览器不支持音频播放')
      }

      if (!audio.value) {
        createAudio()
      }

      state.value.error = null
      
      if (audio.value) {
        audio.value.src = url
        await audio.value.play()
      }
      
      return true
    } catch (error) {
      console.error('播放音频URL失败:', error)
      state.value.error = '音频播放失败'
      return false
    }
  }

  // 从Blob播放音频
  const playFromBlob = async (blob: Blob) => {
    try {
      if (!isSupported) {
        throw new Error('浏览器不支持音频播放')
      }

      if (!audio.value) {
        createAudio()
      }

      state.value.error = null
      
      const audioUrl = URL.createObjectURL(blob)
      
      if (audio.value) {
        audio.value.src = audioUrl
        await audio.value.play()
      }
      
      return true
    } catch (error) {
      console.error('播放Blob音频失败:', error)
      state.value.error = '音频播放失败'
      return false
    }
  }

  // 播放/暂停控制
  const toggle = async () => {
    if (!audio.value) return false

    try {
      if (state.value.isPlaying) {
        audio.value.pause()
      } else {
        await audio.value.play()
      }
      return true
    } catch (error) {
      console.error('播放控制失败:', error)
      state.value.error = '播放控制失败'
      return false
    }
  }

  // 停止播放
  const stop = () => {
    if (audio.value) {
      audio.value.pause()
      audio.value.currentTime = 0
    }
  }

  // 设置音量
  const setVolume = (volume: number) => {
    if (audio.value) {
      audio.value.volume = Math.max(0, Math.min(1, volume))
    }
  }

  // 设置播放进度
  const seek = (time: number) => {
    if (audio.value && state.value.duration > 0) {
      audio.value.currentTime = Math.max(0, Math.min(state.value.duration, time))
    }
  }

  // 清理资源
  const cleanup = () => {
    if (audio.value) {
      audio.value.pause()
      if (audio.value.src && audio.value.src.startsWith('blob:')) {
        URL.revokeObjectURL(audio.value.src)
      }
      audio.value.src = ''
      audio.value = null
    }
    
    state.value.isPlaying = false
    state.value.isPaused = false
    state.value.duration = 0
    state.value.currentTime = 0
    state.value.isLoading = false
    state.value.error = null
  }

  // 格式化时间显示
  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60)
    const secs = Math.floor(seconds % 60)
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }

  // 计算播放进度百分比
  const progress = computed(() => {
    if (state.value.duration === 0) return 0
    return (state.value.currentTime / state.value.duration) * 100
  })

  // 格式化当前时间
  const currentTimeFormatted = computed(() => formatTime(state.value.currentTime))
  
  // 格式化总时长
  const durationFormatted = computed(() => formatTime(state.value.duration))

  return {
    state: computed(() => state.value),
    isSupported,
    playBase64Audio,
    playFromUrl,
    playFromBlob,
    toggle,
    stop,
    setVolume,
    seek,
    cleanup,
    progress,
    currentTimeFormatted,
    durationFormatted,
    formatTime
  }
}